const webpack = require('webpack');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const BundleAnalyzerPlugin =
  require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const plugins = require('./plugins');

const { resolve, root } = require('./utils');
const jsRules = require('./rules/jsRules');
const styleRules = require('./rules/styleRules');
const fileRules = require('./rules/fileRules');

module.exports = {
  mode: 'production',
  entry: {
    main: './src/core/index.tsx',
  },
  output: {
    filename: '[name].[chunkhash].js',
    path: root('dist/'),
    publicPath: '/dist/',
    chunkFilename: '[name].[chunkhash].js',
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx'],
    symlinks: false,
    modules: [resolve('src'), resolve('src/pages'), 'node_modules'], // 告诉 webpack 解析模块时应该搜索的目录。
    plugins: [
      new TsconfigPathsPlugin({
        configFile: resolve('tsconfig.json'),
      }),
    ],
  },
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        parallel: true,
        terserOptions: {
          mangle: true,
          safari10: true,
        },
      }),
      new CssMinimizerPlugin(),
    ],
    splitChunks: {
      cacheGroups: {
        commons: {
          chunks: 'all',
          minChunks: 1,
          priority: 1,
          test: /[\\/]node_modules[\\/]/,
          name: 'vendor',
        },
        styles: {
          name: 'main',
          test: /\/src\/(.*)\.scss$/,
          chunks: 'all',
          enforce: true,
        },
      },
    },
    chunkIds: 'named',
    concatenateModules: true,
    mergeDuplicateChunks: true,
    removeEmptyChunks: true,
    removeAvailableModules: true,
    providedExports: true,
  },
  plugins: [
    ...plugins,
    new CopyPlugin({
      patterns: [
        {
          from: resolve('src/assets'),
          to: resolve('dist/assets'),
        },
      ],
    }),
    new MiniCssExtractPlugin({
      filename: '[name].[chunkhash].css',
      chunkFilename: '[id].[chunkhash].css',
    }),
    new webpack.DefinePlugin({
      'process.env.BROWSER': true,
      'process.env.NODE_ENV': JSON.stringify('production'),
    }),
    new BundleAnalyzerPlugin({
      analyzerMode: 'static',
    }),
  ],
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        include: [resolve('src')],
        use: 'babel-loader',
      },
      ...jsRules,
      ...styleRules,
      ...fileRules,
    ],
  },
};
